const router=require('koa-router')();
const koaBody=require('koa-body');
const events=require('events');
const crypto=require('crypto');
const _=require('underscore');
const {User}=require('../models/index');
const redis=require('../models/redis.server.model');
const checkLogin=require('../middlewares/checkLogin');
const timeLimit=require('../middlewares/timeLimit');
const passwordCharacterLengthLimit=require('../config/config').characterLengthLimit.reg.password;

router.get('/',checkLogin(),async ctx=>{
    let {loginUser}=ctx.session,ee=new events();
    let user=await User.findOne({_id:loginUser._id});
    ee.on('fail',msg=>{
       ctx.flash={error:msg};
       ctx.redirect('back');
    });

    if(!user)return ee.emit('fail','用户不存在');

    await ctx.render('setting',{
        title:'设置',
        loginUser,
        user,
        passwordCharacterLengthLimit,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

router.post('/',checkLogin(),timeLimit({action:'setting'}),koaBody(), async ctx=>{
    let {loginUser}=ctx.session,{body}=ctx.request,{action}=body;

    if('profile'==action){//修改资料
        let user=await User.findOne({_id:loginUser._id},{_id:false,web:true,address:true,weibo:true,github:true,intro:true});
        let data=Object.assign(user,body);

        data=_.pick(data,'web','address','weibo','github','intro');
        if(!data.intro)data.intro='这家伙很懒，什么个性签名都没有留下。';

        await Promise.all([
            User.update({_id:loginUser._id},{$set:data}),
            redis.addLimit({action:'setting',id:loginUser._id})
        ]);
        ctx.session.loginUser=Object.assign(loginUser,data);
        ctx.flash={success:'设置成功'};
        ctx.redirect('/user/'+loginUser._id);
    }else if('password'==action){//修改密码
        let fields=new Map([['origin','原始密码'],['password','新密码'],['repeat','重复密码']]),ee=new events(),data={};
        ee.on('fail',msg=>{
            ctx.flash={error:msg};
            ctx.redirect('back');
        });

        for(let [field,cn] of fields){
            let val=body[field];
            if(!val || !val.trim())return ee.emit('fail',`${cn}未输入`);
            data[field]=val;
        }

        if(data.password.length<passwordCharacterLengthLimit[0] || data.password.length>passwordCharacterLengthLimit[1])return ee.emit('fail',`密码长度非法(${passwordCharacterLengthLimit[0]}~${passwordCharacterLengthLimit[1]})`);
        if(data.password!==data.repeat)return ee.emit('fail','两次密码输入不一致');

        let user=await User.findOne({_id:loginUser._id},{password:true});

        data.origin=crypto.createHash('md5').update(data.origin).digest('hex');
        if(data.origin!==user.password)return ee.emit('fail','原始密码输入错误');

        await User.update({_id:loginUser._id},{$set:{password:crypto.createHash('md5').update(data.password).digest('hex')}});

        delete ctx.session.loginUser;
        ctx.flash={success:'修改密码成功，请重新登录'};
        ctx.redirect('/login');
    }
});

module.exports=router;